# 导入必要的库
import tkinter as tk
from tkinter import ttk
import json
import os
from tkinter import messagebox


class JSONConfigFrame(ttk.Frame):
    def __init__(self, container, json_file):
        super().__init__(container)

        # 初始化配置文件路径
        # self.config_file = os.path.join(os.path.dirname(__file__), 'conf.json')
        self.config_file = json_file
        self.data = {}
        self.is_editing = False

        # 布局组件
        self.create_widgets()

        # 加载配置文件
        self.load_config()

    def create_widgets(self):
        # 文本框用于显示和编辑 JSON 内容
        self.text_area = tk.Text(self, wrap=tk.WORD, state=tk.DISABLED)
        self.text_area.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 修改按钮
        self.edit_button = ttk.Button(
            self, text="修改", command=self.toggle_edit_mode)
        self.edit_button.pack(pady=10)

        # 保存按钮
        save_button = ttk.Button(
            self, text="保存", command=self.save_config, state=tk.DISABLED)
        save_button.pack(pady=10)
        self.save_button = save_button

    def toggle_edit_mode(self):
        if self.is_editing:
            self.text_area.config(state=tk.DISABLED)
            self.edit_button.config(text="修改")
            self.save_button.config(state=tk.DISABLED)
        else:
            # 弹出确认对话框
            confirm = messagebox.askokcancel("确认修改", "修改配置，可能导致程序崩溃，确认要修改吗？")
            if not confirm:
                return
            self.text_area.config(state=tk.NORMAL)
            self.edit_button.config(text="完成")
            self.save_button.config(state=tk.NORMAL)
        self.is_editing = not self.is_editing

    def load_config(self):
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                self.data = json.load(f)
                # 格式化 JSON 内容并显示
                formatted_json = json.dumps(
                    self.data, indent=4, ensure_ascii=False)
                self.text_area.config(state=tk.NORMAL)
                self.text_area.delete(1.0, tk.END)
                self.text_area.insert(tk.END, formatted_json)
                self.text_area.config(state=tk.DISABLED)
        except FileNotFoundError:
            pass
        except json.JSONDecodeError:
            pass

    def save_config(self):
        try:
            # 获取文本框内容
            content = self.text_area.get(1.0, tk.END)
            self.data = json.loads(content)

            # 保存到文件
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.data, f, indent=4, ensure_ascii=False)

            # 提示保存成功
            messagebox.showinfo("提示", "保存成功")
        except json.JSONDecodeError:
            messagebox.showerror("错误", "JSON 格式无效，请检查内容")


class Config_Json_Edit_Win(tk.Toplevel):
    def __init__(self, master, app, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.parent = master
        self.APP = master.APP
        self.MAIN_WINDOW = app.MAIN_WINDOW
        self.setup()

    def setup(self):
        # 创建notebook，每个tab页对应一个json文件
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        # self.json_files = ['config/logcfg.json',
        #    'config/trigger_time.json', 'config/interface_com_map.json']
        # 遍历config文件夹下的json文件，并将文件名放到一个数组中
        self.json_files = []
        for file in os.listdir('config'):
            if file.endswith('.json'):
                self.json_files.append(file)

        # 加载json文件

        # 创建tab页
        for json_file in self.json_files:
            tab = ttk.Frame(self.notebook)
            tab_name = json_file.split('.')[0]
            self.notebook.add(tab, text=tab_name)
            # 创建json配置编辑框
            json_file_path = os.path.join('config', json_file)
            json_config_frame = JSONConfigFrame(tab, json_file_path)
            json_config_frame.pack(fill=tk.BOTH, expand=True)


# 测试
if __name__ == '__main__':
    root = tk.Tk()
    root.geometry('600x600')
    root.title('JSON 配置工具')
    config_frame = JSONConfigFrame(root, 'conf.json')
    config_frame.pack(fill=tk.BOTH, expand=True)
    root.mainloop()
